package arith;

public class Fraction implements Input {

	int num;
	int denom;
	String prob;
	
	public Fraction(int n, int d, String s){
		num = n;
		denom = d;
		prob = s;
	}
	
	public String toString(){
		if(denom == 1){
			return "" + num;
		}else{
			return num + " / " + denom;
		}
	}
	
	public Fraction add(Fraction frac){
		int numerator = num*frac.denom + frac.num*denom;
		int denominator = denom*frac.denom;
		String part1;
		String part2;
		if(this.prob.equalsIgnoreCase("")){
			part1 = this.toString();
		}else{
			part1 = "("+this.prob+")";
		}
		if(frac.prob.equalsIgnoreCase("")){
			part2 = frac.toString();
		}else{
			part2 = "(" + frac.prob + ")";
		}
		return simplify(new Fraction(numerator, denominator, part1+" + "+part2));
	}
	
	public Fraction sub(Fraction frac){
		int numerator = num*frac.denom - frac.num*denom;
		int denominator = denom*frac.denom;
		String part1;
		String part2;
		if(this.prob.equalsIgnoreCase("")){
			part1 = this.toString();
		}else{
			part1 = "("+this.prob+")";
		}
		if(frac.prob.equalsIgnoreCase("")){
			part2 = frac.toString();
		}else{
			part2 = "(" + frac.prob + ")";
		}
		return simplify(new Fraction(numerator, denominator, part1+" - "+part2));
	}

	public Fraction mult(Fraction frac){
		int numerator = num*frac.num;
		int denominator = denom*frac.denom;
		String part1;
		String part2;
		if(this.prob.equalsIgnoreCase("")){
			part1 = this.toString();
		}else{
			part1 = "("+this.prob+")";
		}
		if(frac.prob.equalsIgnoreCase("")){
			part2 = frac.toString();
		}else{
			part2 = "(" + frac.prob + ")";
		}
		return simplify(new Fraction(numerator, denominator, part1+" * "+part2));
	}
	
	//this divided by frac2
	public Fraction div(Fraction frac){
		int numerator = num*frac.denom;
		int denominator = denom*frac.num;
		
		String part1;
		String part2;
		if(this.prob.equalsIgnoreCase("")){
			part1 = this.toString();
		}else{
			part1 = "("+this.prob+")";
		}
		if(frac.prob.equalsIgnoreCase("")){
			part2 = frac.toString();
		}else{
			part2 = "(" + frac.prob + ")";
		}
		return simplify(new Fraction(numerator, denominator, part1+" / "+part2));
	}
	
	private Fraction simplify(Fraction f){
		int factor = gcf(Math.abs(f.num),Math.abs(f.denom));
        f.num = f.num/factor;
        f.denom = f.denom/factor;
        return f;
	}
	
	private int gcf(int n, int d){
		if (n % d == 0){
			return d;
		}else if (d % n == 0){
            return n;
		}else{
            return gcf(n % d, d % n);
		}
    }

	public int id() {
		return 1;
	}

	public double value() {
		return num/denom;
	}

}